package net.jmchilton.spring.collect;

import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * 
 * @author John Chilton
 *
 */
class FactoryMethodTemplateBeanParser extends TemplateBeanParser {

  public FactoryMethodTemplateBeanParser(final String className, final String factoryMethodName) {
    super(className, factoryMethodName);
  }
  
  protected void parseChildren(final Element element, final ParserContext parserContext, final AbstractBeanDefinition definition) {
    final BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
    
    // Parse bean constructor arguments(i.e. arguments to static factory method)
    // No need to verify number arguments, this is handled if the xml is valid
    int i = 0;
    for(final Node childNode : new NodeListIterable(element.getChildNodes())) {
      if(!(childNode instanceof Element)) {
        continue;
      }

      final Element child = (Element) childNode;
      final Object value = delegate.parsePropertySubElement(child, definition);
      final ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
      valueHolder.setSource(parserContext.extractSource(child));
      definition.getConstructorArgumentValues().addIndexedArgumentValue(i++, valueHolder);
    }    
  }
}
